import React, { Component } from "react";
import { Form, Input, Button, Spin, Modal, message, Icon, Upload } from "antd";
import { isAuthenticated } from "../../utils/session";
import { UploadOutline } from "@ant-design/icons";
import { json } from "../../utils/ajax";
import { connect } from "react-redux";
import { getBinaryFromFile } from "../../utils/util";

const { TextArea } = Input;

const store = connect((state) => ({
  user: state.user,
}));

@store
@Form.create()
class CreateModal extends Component {
  state = {
    uploading: false,
    uploadingVideo: false,
    fileList: [],
  };
  onCancel = () => {
    this.props.form.resetFields();
    console.log(this.props, "props");
    this.props.videoVisible(false);
  };
  onOk = () => {
    this.props.form.validateFieldsAndScroll(async (errors, values) => {
      if (!errors) {
        if (!values.file && !values.url) {
          message.info("请上传视频");
          return false;
        }
        console.log(values, "value");
        let url = await this.handleUpload();

        const { file, ...rest } = values;
        let params = {
          ...rest,
          url,
          type: this.props.typeId,
        };
        console.log(params, "params");
        // let res = await json.post('/uploadFile', { file: values.file })
        // this.uploadVideo(values.file)
        this.onCreate(params);
      }
    });
  };
  componentDidMount() {
    if (this.props.typeStr === "edit") {
      console.log("edit");
      const typeData = this.props.typeData;
      this.props.form.setFieldsValue({
        icon: typeData.icon,
      });
      this.props.form.setFieldsValue({
        title: typeData.title,
      });
      this.props.form.setFieldsValue({
        description: typeData.description,
      });
    }
  }
  handleUpload = async () => {
    const { fileList } = this.state;
    const formData = new FormData();
    formData.append("data", fileList[0]);
    this.setState({
      uploading: true,
      uploadingVideo: true,
    });
    let res = await json.post(
      "/uploadFile/video",
      formData,
      {
        // 'Content-Type': 'multipart/form-data;'
      },
      true
    );
    if (res.status === 0) {
      this.setState({
        uploadingVideo: false,
      });
      return res.url;
    }
    // You can use any AJAX library you like
  };
  // async uploadVideo() {
  //   const {
  //     fileList
  //   } = this.state;
  //   console.log(fileList, 'fileList')
  //   const formData = new FormData();
  //   fileList.forEach(file => {
  //     formData.append('files[]', file);
  //   });
  //   let binary = await getBinaryFromFile(fileList[0]);
  //   formData.append("fileData", binary);
  //   console.log(formData)
  //   let res = await json.post('/uploadFile', formData, {
  //     'Content-Type': 'multipart/form-data; boundary=ABCD'
  //   }, true)
  // }
  onCreate = async (values) => {
    let res = await json.post("/video/create", values);
    if (res.status === 0) {
      this.props.onCreated(); //更新外面的数据
      this.onCancel();
    }
  };
  _normFile = (e) => {
    if (e.file.response && e.file.response.data) {
      console.log(e.file.response.data.url, "e.file.response.data.url");
      return e.file.response.data.url;
    } else {
      return "";
    }
  };
  render() {
    const { uploading, fileList, uploadingVideo } = this.state;
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 14,
      },
    };
    let imgUrl = getFieldValue("imgUrl");
    const props = {
      onRemove: (file) => {
        this.setState((state) => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState((state) => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };
    const uploadProps = {
      name: "imgUrl",
      listType: "picture-card",
      headers: {
        Authorization: `Bearer ${isAuthenticated()}`,
      },
      action: `${process.env.REACT_APP_BASE_URL}/upload?isImg=1`,
      showUploadList: false,
      accept: "image/*",
      onChange: (info) => {
        if (info.file.status !== "uploading") {
          this.setState({
            uploading: true,
          });
        }
        if (info.file.status === "done") {
          this.setState({
            uploading: false,
          });
          message.success("上传头像成功");
        } else if (info.file.status === "error") {
          this.setState({
            uploading: false,
          });
          message.error(info.file.response.message || "上传头像失败");
        }
      },
    };
    return (
      <Modal
        visible={this.props.visible}
        title="新增视频"
        centered
        onCancel={this.onCancel}
        okButtonProps={{
          disabled: !this.props.user.isAdmin || fileList.length === 0 || uploadingVideo,
        }}
        onOk={this.onOk}
      >
        {uploadingVideo ? <Spin tip="上传视频中" /> : ""}
        <Form {...formItemLayout}>
          <Form.Item label={"视频名称"}>
            {" "}
            {getFieldDecorator("title", {
              rules: [
                {
                  required: true,
                  message: "请输入视频名称",
                },
              ],
            })(<Input placeholder="请输入视频名称" />)}{" "}
          </Form.Item>{" "}
          <Form.Item label={"视频描述"}>
            {" "}
            {getFieldDecorator("description", {
              rules: [
                {
                  required: true,
                  message: "请输入视频描述",
                },
              ],
            })(<TextArea placeholder="请输入视频描述" />)}{" "}
          </Form.Item>{" "}
          <Form.Item label={"视频主图"}>
            {" "}
            {getFieldDecorator("imgUrl", {
              rules: [
                {
                  required: true,
                  message: "请上传视频主图",
                },
              ],
              getValueFromEvent: this._normFile, //将上传的结果作为表单项的值（用normalize报错了，所以用的这个属性）
            })(
              <Upload {...uploadProps} style={styles.avatarUploader}>
                {" "}
                {imgUrl ? (
                  <img src={imgUrl} alt="icon" style={styles.avatar} />
                ) : (
                  <Icon style={styles.icon} type={uploading ? "loading" : "plus"} />
                )}{" "}
              </Upload>
            )}{" "}
          </Form.Item>{" "}
          <Form.Item label={"视频"}>
            {" "}
            {getFieldDecorator("file", {
              // rules: [{ required: true, message: '请上传视频' }],
              // getValueFromEvent: this._normFile,     //将上传的结果作为表单项的值（用normalize报错了，所以用的这个属性）
            })(
              <Upload {...props}>
                <Button icon="upload"> 点击上传 </Button>{" "}
              </Upload>
            )}{" "}
          </Form.Item>{" "}
        </Form>{" "}
      </Modal>
    );
  }
}

const styles = {
  avatarUploader: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    width: 150,
    height: 150,
    backgroundColor: "#fff",
  },
  icon: {
    fontSize: 28,
    color: "#999",
  },
  avatar: {
    maxWidth: "100%",
    maxHeight: "100%",
  },
};

export default CreateModal;
